<template>
    <Page>
        <div class="datalist">
            <div class="table-header">
                <div class="table-header-right">
                    <el-button type="primary" @click="$router.push({path:'verify/create', query:{}})" plain size="small">新建菜单</el-button>
                </div>
            </div>
            <div>
                <el-tree :data="listData" :props="defaultProps" node-key="id">
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                        <span style="display: inline-block;width: 200px;">{{ data.name }}</span>
                        <el-button
                            type="success"
                            v-if="data.name !=='顶级分类'"
                            size="small"
                            @click="showItem(data, $event)"
                            :style="{ backgroundColor: data.state === 1 ? '#67c23a' : 'red' }"
                            style="margin-left: 40vw;"
                            v-show="data.state === 1 || data.state === 0"
                        >
                            {{ stateMap[data.state] }}
                        </el-button>
                        <el-button
                            type="primary"
                            v-if="data.name !=='顶级分类'"
                            size="small"
                            @click="editItem(data)"
                            style="margin-left: 2vw;background-color: #409eff;"
                        >编辑</el-button>
                        <el-button
                            type="success"
                            v-if="data.name !=='顶级分类'"
                            size="small"
                            @click="addSubCategory(data)"
                            style="margin-left: 10px"
                        >添加子分类</el-button>
                        <el-button
                            type="danger"
                            v-if="data.name !=='顶级分类'"
                            size="small"
                            @click="deleteItem(data)"
                            style="margin-left: 10px"
                        >删除</el-button>
                    </span>
                </el-tree>
            </div>
        </div>
        <Merchant ref="merchant" @refersh="initData"></Merchant>
        <Images ref="image" @refersh="initData"></Images>
    </Page>
</template>

<script>
import Page from "@/components/page/Page";
import Merchant from "./merchant";
import Images from "./images";
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex';

export default {
    data() {
        return {
            listData: [],
            params: {
                applyName: null,
                mchAccount: null,
                dateBegin: null,
                dateEnd: null,
                areaName: null,      // 省市区
                authVerifyStatus: 0,
                currPage: 1,
                pageSize: 25
            },
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            stateMap: {
                '1': '正常',
                '0': '下架',
                '-1': '删除'
            },
            applyDate: [],
            areaCode: [],
            areaArray: [],       // 地区对象
            showButtonText: {}    // 存储按钮显示/隐藏状态
        };
    },
    computed: {
        ...mapState(['mchType']),
        // 根据 state 获取按钮背景颜色

    },
    mounted() {
        this.initData();
        // this.getAreaList();
    },
    methods: {
        getButtonBackgroundColor(data) {
            if (data.state === 1) {
                return '#67c23a';
            } else if (data.state === 0) {
                return'red';
            }
            return '';
        },
        handleNodeClick(data) {
            console.log(data);
        },
        // 初始化数据
        initData() {
            // this.$http.get('/admin/AuthNode/lists', { params: this.params }).then(result => {
            this.$http.get('/admin/AuthNode/listsNew', {params: this.params}).then(result => {
                if (result.code === 200) {
                    const dataObj = result.data;
                    const newListData = [];
                    for (const key in dataObj) {
                        if (dataObj.hasOwnProperty(key)) {
                            newListData.push(dataObj[key]);
                        }
                    }
                    this.listData = newListData;
                    // 初始化按钮状态，state为0时显示'隐藏'
                    this.listData.forEach(item => {
                        this.showButtonText[item.id] = item.state === 0;
                        if (item.children) {
                            item.children.forEach(child => {
                                this.showButtonText[child.id] = child.state === 0;
                            });
                        }
                    });
                } else {
                    this.$message.error(result.msg);
                }
            });
        },
        // 获取地区列表
        getAreaList() {
            this.$http.get('/api/system/areaTree', {}).then(result => {
                if (result.code === 200) {
                    this.areaArray = result.data;
                } else {
                    this.$message.error(result.msg);
                }
            });
        },
        // 切换按钮状态
        showItem(data, event) {
            event.stopPropagation();
            const newState = data.state === 1 ? 0 : 1;
            this.$http.post('/admin/AuthNode/del', {
                id: data.id,
                state: newState
            }).then(result => {
                if (result.code === 200) {
                    data.state = newState;
                    // 更新按钮状态，state为0时显示红色（隐藏状态）
                    this.showButtonText[data.id] = newState === 0;
                    this.$message.success('状态更新成功');
                } else {
                    this.$message.error(result.msg || '状态更新失败');
                }
            }).catch(error => {
                this.$message.error('状态更新失败');
                console.error(error);
            });
        },
        editItem(data) {
            this.$router.push({path:'verify/update', query:{data:data}});
            event.stopPropagation(); // 阻止事件冒泡，避免影响树的展开收起
        },
        addSubCategory(data) {
            this.$router.push({
                path: 'verify/create',
                query: {
                    pid: data.id,
                    pname: data.name,
                    plevel: data.level
                }
            });
            event.stopPropagation(); // 阻止事件冒泡，避免影响树的展开收起
        },
        deleteItem(data) {
            event.stopPropagation(); // 阻止事件冒泡，避免影响树的展开收起
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 用户点击了确定按钮
                this.$http.post('/admin/AuthNode/del', {
                    id: data.id,
                    state: "-1"
                }).then(result => {
                    if (result.code === 200) {
                        this.$message.success(result.msg);
                        this.initData();
                    } else {
                        this.$message.error(result.msg);
                    }
                });
            }).catch(() => {
                // 用户点击了取消按钮
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        }
    },
    components: {
        Page,
        Merchant,
        Images
    }
};
</script>

<style lang="less" scoped>
.el-tree-node__content {
    height: 38px !important;
}

.active-btn {
    background-color: red;
}

.custom-tree-node .el-button {
    transition: background-color 0.3s ease;
}

/deep/ .el-tree-node__content {
    height: 38px !important;
}
</style>
